<template>
  <div class="left" @scroll="wrapperScroll($event)">
    <h3 v-if="state.params.tag_id" class="left-title">
      {{ state.tag_name }} 相关的文章：
    </h3>
    <ul class="articles-list" id="list" ref="ulRef" >
      <transition-group name="el-fade-in">
        <li
          v-for="article in newList"
          :key="article.id"
          class="item"
        >
          <!-- :data-src="article.img_url" -->
          <a :href="state.href + article.id" target="_blank">
            <img
              :data-src="article.img_url"
              class="wrap-img img-blur-done"
              data-has-lazy-src="false"
              src="../assets/img/bg.jpg"
              alt="文章封面"
            />
            <div class="content">
              <h4 class="title">{{ article.title }}</h4>
              <p class="abstract">{{ article.descri }}</p>
            </div>
          </a>
          <div class="meta">
            <span v-if="state.isMy" @click="gotoEdit(article)">编辑</span>
            <span>查看 {{ JSON.parse(article.meta).views }}</span>
            <span>评论 {{ JSON.parse(article.meta).comments }}</span>
            <span>赞 {{ JSON.parse(article.meta).likes }}</span>
            <span v-if="article.create_time" class="time">
              {{ timestampToTime(article.create_time, true) }}
            </span>
          </div>
        </li>
      </transition-group>
    </ul>
    <!-- <LoadingCustom v-if="state.isLoading"></LoadingCustom> -->
    <!-- <LoadEnd v-if="state.isLoadEnd"></LoadEnd> -->
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { GetArticleList } from "../api/api";
import { getQueryByName, timestampToTime, throttle } from "../utils/utils";
import { ArticlesParams, ArticlesData } from "../type/index";
import {
  reactive,
  onMounted,
  watch,
  watchEffect,
  onUpdated,
  computed,
  ref,
  nextTick,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { isMap } from "util/types";
import { useStore } from "vuex";
// import a from  '../assets/img/logo.png'
const store = useStore();
const route = useRoute();
const router = useRouter();
let artiRefresh = ref(false);
let myRefresh = ref(false);
const state = reactive({
  isMy: false,
  isLoadEnd: false,
  isLoading: false,
  articlesList: [],
  // newList:[],
  total: 0,
  tag_name: "",
  params: {
    search: "",
    author: "",
    keyword: "",
    likes: "", // 是否是热门文章
    state: 1, // 文章发布状态 => 0 草稿，1 已发布,'' 代表所有文章
    tag_id: "",
    category_id: "",
    pageNum: 1,
    pageSize: 10,
  } as ArticlesParams,
  href: "http://127.0.0.1:3000/#/articleDetail?article_id=",
  showNum: 1, //视窗内应该显示的 DOM 数量
  startKey: 0, //当前状态索引
  startHeight:0, //列表第一项的高度
  rowHeight:0,
  // ulHeight:0
});
//获取列表DOM
const ulRef=ref();
const viewHeight = window.innerHeight || document.documentElement.clientHeight;

// 用新的 throttle 包装 scroll 的回调
const lazyload = throttle(() => {
  // 获取所有的图片标签
  const imgs = document.querySelectorAll("#list .item img");
  // num 用于统计当前显示到了哪一张图片，避免每次都从第一张图片开始检查是否露出
  let num = 0;
  for (let i = num; i < imgs.length; i++) {
    // 用可视区域高度减去元素顶部距离可视区域顶部的高度
    let distance = viewHeight - imgs[i].getBoundingClientRect().top;
    // console.log("distance:", distance);
    let imgItem: any = imgs[i];
    // 如果可视区域高度大于等于元素顶部距离可视区域顶部的高度，说明元素露出
    if (distance >= 100) {
      // 给元素写入真实的 src，展示图片
      let hasLaySrc = imgItem.getAttribute("data-has-lazy-src");
      if (hasLaySrc === "false") {
        imgItem.src = imgItem.getAttribute("data-src");
        imgItem.setAttribute("data-has-lazy-src", "true");
      }
      // 前 i 张图片已经加载完毕，下次从第 i+1 张开始检查是否露出
      num = i + 1;
    }
  }
}, 1000);

const gotoEdit = (article: any): void => {
  console.log(article);
  router.push({
    path: "edit",
    query: { article_id: article.id },
  });
};
const handleSearch = async (): Promise<void> => {
  // console.log("isMy:",state.isMy)
  state.isLoading = true;
  const res = await GetArticleList(state.params);
  const data = res.data;
  state.isLoading = false;
  state.articlesList = [...data.list];
  state.total = data.count;
  // state.containerHeight = data.count * 96;
  // console.log(state.containerHeight);
  // state.params.pageNum++;

  if (data.list.length === 0 || state.total === state.articlesList.length) {
    // state.isLoadEnd = true;
    // document.removeEventListener("scroll", () => {});
    // window.onscroll = null;
  }
};
//根据路由上的参数去获取响应的文章列表
const routeChange = (val: any, oldVal: any): void => {
  // if(val===oldVal){
  //   console.log('当前页面')
  //   router.go(0)
  // }
  if (val.path === "/my") {
    // console.log(localStorage.getItem())
    state.isMy = true;
    if (!localStorage.getItem("userInfo")) {
      ElMessage({
        message: "请先登录!",
        type: "warning",
      });
      return;
    }
    state.params.author = JSON.parse(localStorage.getItem("userInfo")).name;
    // console.log(JSON.parse(sessionStorage.getItem('userInfo')).name)
  } else {
    state.params.author = "";
    state.isMy = false;
  }
  state.tag_name = val.query.tag_name;
  state.params.tag_id = val.query.tag_id;
  // state.tag_name =val.
  // state.params.tag_id =getQueryByName("tag_id");
  // state.params.category_id = getQueryByName("category_id");
  // console.log(val)
  console.log("name", state.tag_name, "id", state.params.tag_id);

  state.articlesList = [];
  state.params.pageNum = 1;
  handleSearch();
};

//使用watch观察路由变化，记录当前路由
watch(
  route,
  (val, oldVal) => {
    routeChange(val, oldVal);
  },
  { immediate: true }
);

//这里必须要computed才能监测到，computed依赖的值发生变化，computed就能监测到，watch再监测就可以了
artiRefresh = computed(() => {
  return store.state.isArticles;
});
myRefresh = computed(() => {
  return store.state.isMy;
});
watch(
  artiRefresh,
  (val, oldVal) => {
    state.params.search = store.state.searchContent;
    handleSearch();
    store.commit("setIsSearch", false);
    store.commit("setIsAritcles", false);
  },
  { immediate: true, deep: true }
);
watch(
  myRefresh,
  (val, oldVal) => {
    state.params.search = store.state.searchContent;
    state.params.author = JSON.parse(localStorage.getItem("userInfo")).name;
    handleSearch();
    store.commit("setIsSearch", false);
    store.commit("setIsAritcles", false);
  },
  { immediate: true, deep: true }
);

// nextTick(() => {

// });
const newList= computed(() => {
  let endIdx =state.startKey + state.showNum
  if (endIdx >= state.articlesList.length){
         endIdx =state.articlesList.length
  }
  return state.articlesList.slice(state.startKey, endIdx)
  // console.log("end",endIdx)
  // if(state.articlesList.length>0){
  //   if (endIdx >= state.articlesList.length){
  //        endIdx =state.articlesList.length
  //     return state.articlesList.slice(state.startKey, endIdx)
  //    }
  // }
  // return [];
})

watchEffect(() => {
  if (state.articlesList.length > 0) {
    nextTick(() => {
        lazyload();
        // console.log(ulRef.value)
        // console.log(ulRef.value.getBoundingClientRect().top + document.documentElement.scrollTop)
      
      // 列表距离顶部距离
      state.startHeight= ulRef.value.getBoundingClientRect().top + document.documentElement.scrollTop
      // console.log(ulRef.value)
      // console.log(ulRef.value.children[0])
      state.rowHeight = ulRef.value.children[0].offsetHeight
      // if(ulRef.value.children[0]){
        
      // }
      // 计算每行高度
      // state.rowHeight = ulRef.value.children[0].offsetHeight
      // console.log("rowHeight:",state.rowHeight)
      // 计算屏幕内能显示的行数
      // console.log(viewHeight)
      // console.log(state.rowHeight)
      state.showNum= Math.ceil(viewHeight/state.rowHeight)
      // console.log("num",state.showNum)
      // 设置列表总高度 = 一行高度 * 行数
      const listH = state.rowHeight * state.total
      ulRef.value.style.setProperty('height', `${listH}px`)
      window.removeEventListener('scroll', scrollHandler)
      window.addEventListener('scroll', scrollHandler)

    })
  }
})
// nextTick(()=>{
//   lazyload();
// })
// nextTick(()=>{
  
//     state.ulHeight=ulRef.value.clientHeight;
//     state.showNum= Math.ceil(state.ulHeight / state.rowHeight);
//     console.log(ulRef)
//     console.log(state.ulHeight)
//     console.log(state.showNum)

// })
const scrollHandler=()=>{
   lazyload();
  // 当前滚动高度
  const curScrollTop = document.documentElement.scrollTop
  if (curScrollTop > state.startHeight) {
    const addCount = Math.floor((curScrollTop - state.startHeight) / state.rowHeight)
    ulRef.value.style.setProperty('padding-top', `${addCount * state.rowHeight}px`)
    state.startKey = addCount
  } else {
    ulRef.value.style.setProperty('padding-top', '0px')
    state.startKey = 0
  }
}
// const newList= computed(() => { 
//   console.log( [...state.articlesList.slice(state.startKey, state.showNum+ state.startKey + 3)]) 
//   return [...state.articlesList.slice(state.startKey, state.showNum+ state.startKey + 3)];
// });

onMounted(() => {
  // console.log(store.state.user.userInfo.userInfo.id)
  //从搜索跳转过来的
  if (store.state.isSearch) {
    state.params.search = store.state.searchContent;
    store.commit("setIsSearch", false);
  }
  // console.log("viewHeight:",viewHeight)
  handleSearch();
  document.addEventListener("scroll", scrollHandler);
  // state.showNum=
});
// onCreated(())
</script>

<style scoped lang="less">
.left {
  .articles-list {
    margin: 0;
    padding: 0;
    list-style: none;
    .title {
      color: #333;
      margin: 7px 0 4px;
      display: inherit;
      font-size: 18px;
      font-weight: 700;
      line-height: 1.5;
    }
    .item > div {
      padding-right: 140px;
    }
    .item .wrap-img {
      position: absolute;
      top: 50%;
      margin-top: -50px;
      right: 0;
      width: 125px;
      height: 100px;
      img {
        width: 100%;
        height: 100%;
        border-radius: 4px;
        border: 1px solid #f0f0f0;
      }
    }
    li {
      line-height: 20px;
      position: relative;
      // width: 100%;
      padding: 15px 0px;
      padding-right: 150px;
      border-bottom: 1px solid #f0f0f0;
      word-wrap: break-word;
      cursor: pointer;
      &:hover {
        .title {
          color: #000;
        }
      }
      .abstract {
        min-height: 30px;
        margin: 0 0 8px;
        font-size: 13px;
        line-height: 24px;
        color: #555;
      }
      .meta {
        padding-right: 0 !important;
        font-size: 12px;
        font-weight: 400;
        line-height: 20px;
        a {
          margin-right: 10px;
          color: #b4b4b4;
          &::hover {
            transition: 0.1s ease-in;
            -webkit-transition: 0.1s ease-in;
            -moz-transition: 0.1s ease-in;
            -o-transition: 0.1s ease-in;
            -ms-transition: 0.1s ease-in;
          }
        }
        span {
          margin-right: 10px;
          color: #666;
        }
      }
    }
  }
}
</style>
